package com.cloudptt.wp.ui.main;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.TextView;

import com.cloudptt.api.product.NetworkListener;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.adapter.GCallEventAdapter;
import com.cloudptt.api.product.adapter.ICallInfoDesc;
import com.cloudptt.api.product.func.message.MsgListener;
import com.cloudptt.api.product.func.sys.SysStateInfo;
import com.cloudptt.api.product.func.sys.listener.SysListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.AddrOperator;
import com.cloudptt.api.product.update.UpdateListener;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.menu.MenuActivity;
import com.cloudptt.wp.ui.more.SettingActivity;
import com.mcptt.config.local.SysConfig;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.http.operator.IHttpAddrOpCb;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity implements SysListener
		, NetworkListener, UpdateListener,MsgListener, ICallInfoDesc, IHttpAddrOpCb {

	public static String THIS_FILE = "MainActivity";
	public final static String KEY_HOME = "MainActivity";
	public final static String KEY_NAME_ISFIRST = "isFirstLogin";
	private TextView id_notify = null;
	public TextView    groupNameTextView = null;
	public Button menuBtn = null;
	public Button settingBtn = null;
	public TextView    callRightTextView = null;
	private WakeLock wakeLock;
	private Product product = null;
	private GCallEventAdapter callEventAdapter = null;

	/** permission request 2019/07/15 **/
	private final static int OVERLAY_REQUEST_CODE = 10;
	private static final int PERMISSION_REQUEST_STORAGE = 1;
	private List<String> mPermissionList = new ArrayList<String>();
	private String[] mPermissions = new String[] {
			Manifest.permission.CHANGE_NETWORK_STATE,
			Manifest.permission.CALL_PHONE,
			Manifest.permission.INTERNET,
			Manifest.permission.MODIFY_AUDIO_SETTINGS,
			Manifest.permission.READ_PHONE_STATE,
			Manifest.permission.RECEIVE_BOOT_COMPLETED,
			Manifest.permission.WRITE_CONTACTS,
			Manifest.permission.WAKE_LOCK,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.BLUETOOTH,
			Manifest.permission.BLUETOOTH_ADMIN,
			Manifest.permission.USE_SIP,
			Manifest.permission.CAMERA,
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.RECORD_AUDIO,
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(THIS_FILE, "On onCreate");
		setContentView(R.layout.activity_main);

		groupNameTextView = (TextView) findViewById(R.id.nameTextView);
		callRightTextView = (TextView) findViewById(R.id.numTextView);
		settingBtn = (Button) findViewById(R.id.rightBtn);
		menuBtn = (Button) findViewById(R.id.leftBtn);
		initView();

		ScreenManager.getScreenManager().pushActivity(this);
	}

	@Override
	protected void onResume() {
		Log.i(THIS_FILE, "On Resume");
		super.onResume();
		checkPermission();

		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			product = app.getProduct();
		}
		if(product != null) {
			product.setNetworkListener(this);
			product.setSysListener(this.getClass().getName(),this);
			product.setMsgListener(this,null);
			product.setUpdateListener(this);

			resetSvrStatueDscp();
		}

		if( product != null)
		{
			if(callEventAdapter == null)
			{
				callEventAdapter = product.getGCallEventAdapter();
			}
			callEventAdapter.setCallInfoDesc(this);
			updateGroupName();
		}

		updateGroupName();
		resetSvrStatueDscp();
	}

	private void resetSvrStatueDscp() {
		if (id_notify != null) {
			SysApplication app = ((SysApplication) getApplicationContext());
			if(product != null)
			{
				String srvStatusDscp = product.getSrvStatusDscp();
				id_notify.setText(srvStatusDscp);
			}

		}
	}

	public void updateGroupName() {
		Log.i(THIS_FILE, " updateGroupName" );
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			product = app.getProduct();
		}

		if (product != null && product.getCurGroupInfo() != null) {

			String groupName = product.getCurGroupInfo().getName();
			Log.i(THIS_FILE, " updateGroupName groupName = " + groupName);
			groupNameTextView.setText(groupName);
		} else {
			groupNameTextView.setText("");
		}
	}

	@Override
	public void finish() {
		Log.i(THIS_FILE, " finish()");
		super.finish();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		Log.i(THIS_FILE, " onDestroy()");
		
		
		if (wakeLock!= null) 
		{          
			try 
			{
				wakeLock.release();
            } catch (Throwable th) {
                // ignoring this exception, probably wakeLock was already released
            }
			 wakeLock = null; 
		}
		super.onDestroy();
	}

//	private void goToLogin() {
//		Log.i(THIS_FILE, " goToLogin()");
//		Intent intent = new Intent();
//		intent.setClass(MainActivity.this, Login.class);
//		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//		startActivity(intent);
//	}

	private void initView() {

		Log.i(THIS_FILE, "mainactiviy initView");
		setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);

		id_notify = (TextView) findViewById(R.id.id_notify);

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(THIS_FILE, "onKeyDown keyCode "+ keyCode);

		if (keyCode == KeyEvent.KEYCODE_SOFT_LEFT)
		{
			gotoMenuActivity();
		}
		else if (keyCode == KeyEvent.KEYCODE_BACK) {
			gotoSettingActivity();
			if(getFragmentManager().getBackStackEntryCount()>0)
			{
				Log.d(THIS_FILE, "count :"
					+ getFragmentManager().getBackStackEntryCount());
				getFragmentManager().popBackStackImmediate();
			}
			Log.d(THIS_FILE, "onKeyDown end");
			return false;
		}
//		else if (keyCode == KeyEvent.KEYCODE_MENU) {
//		    super.openOptionsMenu();  // 调用这个，就可以弹出菜单
//		}
		else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ){
			AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			am.adjustStreamVolume( AudioManager.STREAM_VOICE_CALL, AudioManager.ADJUST_LOWER,
					AudioManager.FLAG_SHOW_UI  );
            return true;
        }else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
        	AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        	am.adjustStreamVolume( AudioManager.STREAM_VOICE_CALL, AudioManager.ADJUST_RAISE,
        			AudioManager.FLAG_SHOW_UI );
        	return true;
        }
//		else if(keyCode == 142){
//			if(callEventAdapter != null)
//			{
//				callEventAdapter.onPtt(Const.MSG_TALK_ON,false);
//			}
//			return true;
//		}
		return super.onKeyDown(keyCode, event);
	}


	private void gotoMenuActivity()
	{
		Intent intent = new Intent(MainActivity.this,
				MenuActivity.class);
		startActivity(intent);
		overridePendingTransition( R.anim.in_from_left, R.anim.out_to_right );
	}

	private void gotoSettingActivity()
	{
		Intent intent = new Intent(MainActivity.this,
				SettingActivity.class);
		startActivity(intent);
		overridePendingTransition( R.anim.in_from_left, R.anim.out_to_right );
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		Log.d(THIS_FILE, "onKeyUp keyCode "+ keyCode);
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void networkChange(boolean isConnect) {
		resetSvrStatueDscp();
	}

	@Override
	public void updateCallUser(String callKey, boolean isShow, String userDesc) {
		Log.d(THIS_FILE, "updateCallUser callKey = " + callKey + " isShow = " + isShow + " userDesc = " + userDesc);
		callRightTextView.setText(userDesc);

	}

	@Override
	public void updateCallInfoDesc(String callKey, int callState,String callInfoDesc) {
		Log.d(THIS_FILE, "updateCallInfoDesc callKey = " + callKey + " callInfoDesc = " + callInfoDesc);
		callRightTextView.setText(callInfoDesc);
		updateGroupName();
	}
	@Override
	public void updateFloorInfoDesc(String callKey, int speakState, String floorInfoDesc) {

	}
	@Override
	public void updateFloorState(String callKey,int speakState,boolean hasVoice)
	{}
	@Override
	public void updateSecDesc(String callKey, String secStr) {

	}

	@Override
	public void receiveMsg() {

	}

	@Override
	public void onSysState(SysStateInfo stateInfo) {
		resetSvrStatueDscp();
		Log.d(THIS_FILE, "onSysState stateInfo = " + stateInfo);
		int state = stateInfo.getState();
		int cause = stateInfo.getCause();
		Log.d(THIS_FILE, "onSysState state = " + state);
		if(SysStateInfo.SysState_SvrStartState == state)
		{
			if(SysStateInfo.Cause_Failed == cause
					|| SysStateInfo.Cause_Timeout == cause
					|| SysStateInfo.Cause_Password == cause)
			{
				id_notify.setText(R.string.login_failed);
			}
		}
		else if(SysStateInfo.SysState_SipAuthSucState == state)
		{
			if(product == null){
				SysApplication app = ((SysApplication) getApplicationContext());
				this.product = app.getProduct();
			}

			if( product != null)
			{
				loadAddrList();

				if(callEventAdapter == null)
				{
					callEventAdapter = product.getGCallEventAdapter();
				}
				callEventAdapter.setCallInfoDesc(this);

//				Log.d(THIS_FILE,"onSysState makeGroupCall stateInfo = " + stateInfo);
//				callEventAdapter.makeGroupCall();
			}
		}
	}
	@Override
	public void onErrer(String str)
	{

	}

	@Override
	public void onForceDetach() {

	}

	@Override
	public void onKeepAlive(boolean isconnected) {

	}

	@Override
	public void onSvrRestart() {

	}

//	@Override
//	public void initConfigSuc(String fileName)
//	{
//
//	}
//	@Override
//	public void initConfigFailed(String fileName,String errStr)
//	{
//
//	}

	@Override
	public void onUpdate(int state) {

	}


	public void loadAddrList()
	{
		SysConfig config = product.getSysConfig();//.getServerInfo().getServerIp();
		Log.d(THIS_FILE, "loadAddrList config = " + config);
		if(config != null)
		{
			AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
			op.loadAddress(config, this);//.loadAddressAndOnline(svrIp, this);
		}
	}

	@Override
	public void onAddrUptResult(boolean isSuc) {
		Log.d(THIS_FILE, "onAddrUptResult isSuc = " + isSuc);
		if(isSuc)
		{
			this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					updateAddrList();
				}
			});
		}
	}

	@Override
	public void onOnlineUptResult(boolean isSuc) {

	}

	private void updateAddrList(){
		if(product == null){
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}
		updateGroupName();
	}


	private void checkPermission() {
		if (Build.VERSION.SDK_INT >= 23)
		{
			mPermissionList.clear();
			for (String permission : mPermissions)
			{
				if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
				{
					mPermissionList.add(permission);
				}
			}

			Log.d(THIS_FILE, "mPermissionList = "+mPermissionList);
			if (!mPermissionList.isEmpty()) {
				String[] reqpermissions = mPermissionList.toArray(new String[mPermissionList.size()]);
				requestPermissions(reqpermissions, PERMISSION_REQUEST_STORAGE);
			} else if(!Settings.canDrawOverlays(getApplicationContext())){
				startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName())), OVERLAY_REQUEST_CODE);
			}
			else{
			}
		}
		((SysApplication) getApplication()).creatProduct();
	}
}
